package cn.com.connext.scrm.repository.master;

import cn.com.connext.scrm.domain.master.Activity;
import cn.com.connext.scrm.domain.master.SystemMessageUserLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface SystemMessageUserLogRepository extends JpaRepository<SystemMessageUserLog,String>, JpaSpecificationExecutor {
    List<SystemMessageUserLog> findByMessageId(String id);

    @Modifying
    @Query(value = "delete from system_message_user_log where message_id = ?1", nativeQuery = true)
    void deleteById(String id);

    @Modifying
    @Query(value = "INSERT INTO `system_message_user_log` (`user_id`, `message_id`, `type`, `create_time`, `update_time`, `is_send`, `is_read`, `is_show`) " +
        "select union_id, ?1, 0, now(), now(), 0, 0, ?2 from `mini_program_user` where union_id is not null", nativeQuery = true)
    void saveAllLog(String id, Boolean show);

    @Modifying
    @Query(value = "INSERT INTO `system_message_user_log` (`user_id`, `message_id`, `type`, `create_time`, `update_time`, `is_send`, `is_read`, `is_show`) " +
        "select union_id, ?1, 0, now(), now(), 0, 0, ?2 from `mini_program_user` where union_id is not null and union_id in (?3)", nativeQuery = true)
    void saveLogInUserId(String id, Boolean show, String[] userIds);

    @Modifying
    @Query(value = "INSERT INTO `system_message_user_log` (`user_id`, `message_id`, `type`, `create_time`, `update_time`, `is_send`, `is_read`, `is_show`) " +
        "select union_id, ?1, 0, now(), now(), 0, 0, ?2 from `mini_program_user` where union_id is not null and union_id = ?3 ", nativeQuery = true)
    void saveByUserId(String id, Boolean show, String userId);

    @Query(value = "select count(s) from SystemMessageUserLog s where s.isSend = true and s.isRead = false and s.userId = ?1 ")
    Integer findCountByUserId(String userId);
}
